package com.eascs.loansettled.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.Format;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.eascs.account.account.AccountEntity;
import com.eascs.admin.o2o.internal.entity.LoanapplyExpand;
import com.eascs.admin.o2o.internal.service.LoanapplyExpandService;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oChargeSituationService;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.recordlog.constant.O2oLogType;
import com.eascs.admin.recordlog.servcie.O2oRecordLogService;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.StringUtil;
import com.eascs.loan.entity.O2oBankLoanData;
import com.eascs.loan.service.O2oLoanService;
import com.eascs.loansettled.service.O2oLoanSettledService;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.type.SystemModule;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
@RequestMapping("/rloansettled")
public class O2oLoanSettledRestController extends BaseRestController {
	private static Logger log = LoggerFactory.getLogger(O2oLoanSettledRestController.class);

	@Autowired
	O2oLoanSettledService loanSettledService;

	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Autowired
	private O2oRecordLogService o2oRecordLogService;
	@Autowired
	private LoanapplyExpandService loanapplyExpandService;
	@Autowired
	private O2oLoanUserService o2oLoanUserService;

	@Autowired
	private O2oLoanService o2oLoanService;
	@Autowired
	private BaseUtils baseUtils;
	@Value("${o2o.admin.iframe.domain}")
	private String domain;
	
	@Autowired
	O2oChargeSituationService o2oChargeSituationService;

	@RequestMapping("/detail")
	public BaseRestResult<String> detail(String loanapplyNo) {
		O2oLoanapplyEntity loan = o2oLoanapplyService.findById(loanapplyNo);
		LoanapplyExpand loanapplyExpand = loanapplyExpandService.queryLoanapplyNo(loanapplyNo);
		O2oLoanUserEntity loanUser = o2oLoanUserService.findById(loan.getLoanId(), loanapplyNo);
		O2oBankLoanData bankData = o2oLoanService.queryBillCode(loan.getBillCode());
		// 审批详情
		String agreeUrl = baseUtils.getApprovalAgreeUrl(loanapplyNo, null, SystemModule.SYSTEM_MODULE_O2O);
		ViewContext.put("loanapply", loan);
		ViewContext.put("loanapplyExpand", loanapplyExpand);
		ViewContext.put("loanUser", loanUser);
		ViewContext.put("bankData", bankData);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("domain", domain);

		PageResult<Object[]> pageResult = loanSettledService.findHistoryPayments(loan.getBankActno());
		String[] titles = { "还款期号", "交易日期", "应还款日期", "还本金额 ", "还息金额", "本金罚息", "利息罚息", "本金罚息的罚息" };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(0);
		ViewContext.put("paginationInfoss", paginationInfo);
		return HtmlRestResult.popHtmlFragment("loansettled/loansettled_detail");
	}

	@RequestMapping("/upoa")
	public BaseRestResult<String> upoa(HttpServletRequest request) {
		String[] billCode = request.getParameterValues("ids");
		if (billCode == null || billCode.length == 0) {
			return BaseRestResult.warn("请选中需要结清的单");
		}
		StringBuffer billcodes = new StringBuffer();//查询所有已勾选的贷款ID
		StringBuffer billcode_update = new StringBuffer();//查询已勾选并已缴纳的贷款ID
		int j=0;
		StringBuffer billcode_update_id = new StringBuffer();//查询已勾选并已缴纳的贷款ID
		StringBuffer billcode_updated = new StringBuffer();//查询已勾选并未缴纳的贷款ID
		for (int i = 0; i < billCode.length; i++) {
			billcodes.append("'" + billCode[i] + "',");
			AccountEntity accountEntity = o2oChargeSituationService.queryLoanAccount(billCode[i], "311");
			if (null == accountEntity || null == accountEntity.getBalance() || accountEntity.getBalance().compareTo(BigDecimal.ZERO) == 0) {
				O2oLoanapplyEntity loanapplyEntity = o2oLoanapplyService.findById(billCode[i]);
				billcode_updated.append(loanapplyEntity.getBillCode() + ",");
			} else {
				j++;
				billcode_update.append(billCode[i] + ",");
				billcode_update_id.append("'" + billCode[i] + "',");
			}
		}
		if (billcode_update.length() == 0) {
			billcode_update.append(",");
		}
		if (billcode_updated.length() == 0) {
			billcode_updated.append(",");
		}
		if (billcode_update_id.length() == 0) {
			billcode_update_id.append(",");
		}
//		String billcode_ = "";
		String billcode_update_ = "";
		String billcode_updated_ = "";
		String billcode_update_id_ = "";
//		billcode_ = billcodes.substring(0, billcodes.length() - 1);
		billcode_update_ = billcode_update.substring(0, billcode_update.length() - 1);
		billcode_updated_ = billcode_updated.substring(0, billcode_updated.length()-1);
		billcode_update_id_ = billcode_update_id.substring(0, billcode_update_id.length()-1);

		// PageResult<Object[]> pageResult =
		// loanSettledService.findByPage(entity);
		PageResult<Object[]> pageResult = new PageResult<Object[]>();
		if(StringUtil.isNotBlank(billcode_update_)){
			pageResult = loanSettledService.findUdateByO2oPage(billcode_update_id_);
		}
		String[] titles = { "贷款单号", "借款人姓名", "银行", "平台名称", "贷款类型", "省区", "放款金额", "放款日期", "到期日期" };
		SelectDataOption[] selectDataOptions = { null, null, new SelectDataOption("BANKTYPEO2O"), null,
				new SelectDataOption("OTO_LOAN_TYPE"), null, null, null };
		Button[] titleButtons = new Button[] { ButtonHelper.createOpenButton(null, "/detail?loanapplyNo=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setFormats(
				new Format[] { null, null, null, null, null, null, new DecimalFormat(",##0.00"), null, null });
		ViewContext.put("paginationInfoss", paginationInfo);
		ViewContext.put("ids", billcode_update_);
		ViewContext.put("billcodes", billcode_updated_);
		ViewContext.put("billLength", j);
		return HtmlRestResult.popHtmlFragment("loansettled/checkloansettled");
	}

	//结清确认--批量确认结清
	@RequestMapping("/upoaando2o")
	public BaseRestResult<String> update(String ids, String loansettleddate) {
		if (StringUtil.isBlank(loansettleddate)) {
			return BaseRestResult.warn("请选择结清日期");
		}
		if (StringUtil.isBlank(ids)) {
			return BaseRestResult.warn("请选择已缴保证金的单号");
		}
		int j = loanSettledService.updateLoanStatus(ids, loansettleddate);
		if (j > 0) {
			log.debug("贷款单号为：{}  手动结清成功", ids);
		} else {
			log.debug("贷款单号为：{}  手动结清失败", ids);
		}
		// 记录到操作日志表
		String[] id = ids.split(",");
		O2oLoanapplyEntity O2oLoanapplyUp = null;
		O2oLoanapplyEntity O2oLoanapplyDown = null;
		for (int i = 0; i < id.length; i++) {
			ObjectMapper mapper = new ObjectMapper();
			O2oLoanapplyUp = o2oLoanapplyService.findById(id[i]);
			if (O2oLoanapplyUp != null) {
				O2oLoanapplyDown = O2oLoanapplyUp;
				O2oLoanapplyDown.setSettleDate(DateUtils.formateStandDate(loansettleddate));
				O2oLoanapplyDown.setWfType(StatusContexts.O2O_REPAY_END);
				try {
					/*o2oLoanapplyService.saveLog(UserHolder.getUser().getCname(), O2oLogType.PARTNER_UPDATE_SETTLE,
							mapper.writeValueAsString(O2oLoanapplyUp), mapper.writeValueAsString(O2oLoanapplyDown));*/
					// 记录到操作日志表
					o2oLoanapplyService.saveLog(UserHolder.getUser().getCname(), O2oLogType.LOAN_STATUS_HN,
							mapper.writeValueAsString(O2oLoanapplyUp), mapper.writeValueAsString(O2oLoanapplyDown));
					// 记录到【结清操作记录】和【作废操作记录】 日志表
					o2oRecordLogService.saveLog(O2oLoanapplyDown.getBillCode(), UserHolder.getUser().getCname(), O2oLogType.LOAN_STATUS_HN, O2oLoanapplyDown.getSettleDate(), O2oLoanapplyDown.getRemark(),"录入");
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				log.debug("贷款单号为：{} 此单不存在", id[i]);
			}
		}
		return BaseRestResult.info("手动结清成功").andRefresh();
	}

}
